package net.lesscoding.demo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import net.lesscoding.Const;

import java.nio.charset.StandardCharsets;

/**
 * @author eleven
 * @date 2024/10/29 14:09
 * @apiNote
 */
public class EchoServer {
    public static void main(String[] args) {
        new ServerBootstrap()
                .channel(NioServerSocketChannel.class)
                .group(new NioEventLoopGroup())
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel channel) throws Exception {
                        channel.pipeline()
                                .addLast(new StringDecoder())
                                .addLast(new ChannelInboundHandlerAdapter(){
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                        System.out.println(msg);
                                        // 网客户端写入数据
                                        ByteBuf response = ctx.alloc().buffer();
                                        response.writeBytes("hello world client".getBytes(StandardCharsets.UTF_8));
                                        ctx.writeAndFlush(response);
                                        System.out.println("写出数据 :" + response);
                                        super.channelRead(ctx, msg);
                                        response.release();
                                    }
                                });
                    }
                })
                .bind(Const.PORT)
        ;
    }
}
